/**
 * 手机号格式化(中间四位用星号显示)
 * @param {String} phone
 */
export let formatPhone = phone => {
  phone = phone.toString();
  return phone.substr(0, 3) + "****" + phone.substr(7, 11);
};

/**
 * 格式化银行卡（4位一空格）
 * @param {String} bank
 */
export let formatBank = bank => {
  if (bank) {
    return bank
      .toString()
      .replace(/\s/g, "")
      .replace(/(.{4})/g, "$1 ");
  }
};

/**
 * 千分位格式化
 * @param {数字} number // 数字
 */
export let toThousands = number => {
  let num = (number || 0).toString();
  let result = "";
  while (num.length > 3) {
    result = "," + num.slice(-3) + result;
    num = num.slice(0, num.length - 3);
  }
  if (num) {
    result = num + result;
  }
  return result;
};

/**
 * 超出长度用自定义文本显示(默认4位省略号显示)
 * @param {String} str   // 需要操作的字符串
 * @param {number} num     // 超过位数
 * @param {String} text  // 拼接的字符串
 */
export let omitString = (str, num = 3, text = "...") => {
  if (str) {
    return str.toString().substring(0, num) + text;
  }
};

/**
 * 数字补零（小于十的数字前面补零）
 * @param {number} num     // 超过位数
 */
export let add0 = num => {
  return num.toString().padStart(2, 0);
};
/**
 * 取小数点
 * @param {*} value
 * @param {*} num
 */
export function toFixed(value, num) {
  if (!value) return "";
  let _num = num || 2;
  if (typeof value == "number") {
    return value.toFixed(_num);
  } else {
    return parseFloat(value).toFixed(_num);
  }
}
/**
 * 防止XSS攻击
 * @param {*} value
 */
export function unescape(value) {
  if (!value) return "";
  let escapeMap = {
    "&amp;": "&",
    "&lt;": "<",
    "&gt;": ">",
    "&quot;": '"',
    "&#x27;": "'",
    "&#x60;": "`"
  };
  return value.replace(/&(lt|gt|amp|quot|#x27|#x60);/gi, function(t) {
    return escapeMap[t];
  });
}
